package com.kbt.activity;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.Image;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.*;
import com.android.volley.Request;
import com.google.gson.Gson;
import com.kbt.base.BaseApplication;
import com.kbt.commont.Constants;
import com.kbt.model.data.BaseBean;
import com.kbt.model.data.JiFenBean;
import com.kbt.model.data.JiFenBeans;
import com.kbt.net.RequestManager;
import com.kbt.util.tool.TimeCountUtil;
import com.kbt.util.tool.UUIDUtilTool;
import com.kbt.util.utils.SharePreferenceUtils;
import com.kbt.util.utils.Utils;

import javax.sql.RowSetListener;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @Title: KBT_ANDRIOD
 * @Copyright: KJ Co., Ltd. Copyright 2015-2020,  All rights reserved
 * @Description: ${todo}实名认证
 * @author: zhgk
 * @data: 2015/8/17 15:45
 * @version: V1.0
 */
public class RenZhengActivity extends Activity implements RequestManager.ResponseInterface{

    private RequestManager mRequestManager;
    private Map<String, String> postMap =null;
    private Map<String,Object> map=null;
    private SharePreferenceUtils share;
    private String phone;
    private EditText phone_number;//手机号
    private EditText userName;//姓名
    private EditText zf_zh;//支付账号
    private EditText imageCode;//图形码
    private EditText yaoQing_code;//邀请码
    private EditText phone_code;//手机验证码
    private ImageView image_code_view;//图形验证码图片
    private String uuId;
    private Button tv_commit;
    private Button bt_get_verification_code;//获取验证码
    private TimeCountUtil timer;
    private BaseBean baseBean;
    private String payWay;//支付方式(1.支付宝支付 2.微信支付)
    private ImageView weixin_image;
    private ImageView zhifubao_image;
    private RelativeLayout rl_weixin;
    private RelativeLayout rl_zhifubao;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.user_renzheng);
        this.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_return_btn);
        //设置返回按钮事件,关闭当前Activity，返回数据
        ImageView returnImg = (ImageView) findViewById(R.id.return_btn);
        returnImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //不创建地址
                setResult(RESULT_CANCELED, null);
                BaseApplication.getInstance().removeActivity(RenZhengActivity.this);
                finish();
            }
        });

        TextView appTitleView = (TextView) findViewById(R.id.center_title);
        appTitleView.setText("绑定提现账号");

        // 访问网络能在主程序中进行
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads()
                .detectDiskWrites()
                .detectNetwork()
                .penaltyLog()
                .build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects()
                .detectLeakedClosableObjects()
                .penaltyLog()
                .penaltyDeath()
                .build());

        uuId= UUIDUtilTool.getUUID();

        init();
        //监听
        setListener();
    }
    //监听
    private void setListener(){
        //图片验证码点击事件
        image_code_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uuId= UUIDUtilTool.getUUID();
                String urlString = Constants.ServiceInterFace.ServerURL + "rest/api/v1.1/valid_code?valid_code_id="+uuId;
                URL imageUrl = null;
                Bitmap bitmap = null;
                try{
                    imageUrl = new URL(urlString);
                }catch (MalformedURLException e) {
                    // TODO: handle exception
                    Log.e("TAG", "MalformedURLException");
                    e.printStackTrace();
                }
                try{
                    HttpURLConnection connection = (HttpURLConnection)imageUrl.openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    //将得到的数据转换为InputStream
                    InputStream is = connection.getInputStream();
                    //将InputStream转换为Bitmap
                    bitmap = BitmapFactory.decodeStream(is);
                    is.close();
                }catch (IOException e) {
                    // TODO: handle exception
                    Log.e("TAG", "IOException");
                }
                if(bitmap == null){
                    Log.i("TAG", "没取到数据");
                }else{
                    image_code_view.setImageBitmap(bitmap);
                }
            }
        });
        //提交点击事件
        tv_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String name = userName.getText().toString();
                String zhanghao=zf_zh.getText().toString();
                String image_code = imageCode.getText().toString();
                String phoneCode=phone_code.getText().toString();
                String yaoqingCode = yaoQing_code.getText().toString();
                if(name.length()==0){
                    Toast.makeText(v.getContext(), "请输入姓名", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(zhanghao.length()==0){
                    Toast.makeText(v.getContext(), "请输入提现账号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(image_code.length()==0){
                    Toast.makeText(v.getContext(), "请输入图片验证码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(phoneCode.length()==0){
                    Toast.makeText(v.getContext(), "请输入手机验证码", Toast.LENGTH_SHORT).show();
                    return;
                }
                httpCommit(name,zhanghao,image_code,phoneCode,yaoqingCode);

            }
        });
        //获取验证码
        bt_get_verification_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String image_Code =imageCode.getText().toString().trim();
                if (image_Code.length() == 0) {
                    Toast.makeText(v.getContext(), "请输入图片验证码", Toast.LENGTH_SHORT).show();
                    return;
                }
                httpYanZhengCode(image_Code);
            }
        });
        rl_weixin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                payWay = "2";
                weixin_image
                        .setImageResource(R.drawable.checkbox2_selected);
                zhifubao_image
                        .setImageResource(R.drawable.checkbox2_unselect);
            }
        });
        rl_zhifubao.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                payWay = "1";
                weixin_image
                        .setImageResource(R.drawable.checkbox2_unselect);
                zhifubao_image
                        .setImageResource(R.drawable.checkbox2_selected);
            }
        });
    }
    //获取验证码
    private void httpYanZhengCode(String image_Code){
        if(Utils.isNetworkAvailable(RenZhengActivity.this)) {
            mRequestManager.requestGet(Request.Method.GET, Constants.ServiceInterFace.getCodeURL + phone + "&valid_code_value="+image_Code+"&valid_code_id="+uuId, Constants.RequestTag.getCodeTag, map, BaseBean.class);
        }else{
            Toast.makeText(RenZhengActivity.this,R.string.Wangluo,Toast.LENGTH_SHORT).show();
        }
    }
    //提交
    private void httpCommit(String name,String zhanghao,String image_code,String phoneCode,String yaoqingCode){
        if(Utils.isNetworkAvailable(RenZhengActivity.this)) {
            postMap.clear();
            Gson gson = new Gson();
            Map dataMap = new HashMap<String,String>();
            dataMap.put("user_mobile",phone);
            dataMap.put("user_name",name);
            dataMap.put("user_ac_type",payWay);
            dataMap.put("user_ac_account",zhanghao);
            dataMap.put("user_code",phoneCode);
            dataMap.put("valid_code_id", uuId);
            dataMap.put("valid_code_value",image_code);
            dataMap.put("user_key",yaoqingCode);
            postMap.put("data", gson.toJson(dataMap));
            mRequestManager.post(Constants.ServiceInterFace.shiMingUrl, postMap, Constants.RequestTag.shiMingTag, BaseBean.class);
        }else{
            Toast.makeText(RenZhengActivity.this,R.string.Wangluo,Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    protected void onStart() {
        super.onStart();
    }
    //初始化
    public void init(){
        weixin_image = (ImageView) findViewById(R.id.weixin_image);
        zhifubao_image = (ImageView) findViewById(R.id.zhifubao_image);
        rl_weixin = (RelativeLayout) findViewById(R.id.rl_weixin);
        rl_zhifubao = (RelativeLayout) findViewById(R.id.rl_zhifubao);
        //默认选择支付宝
        payWay = "1";
        weixin_image
                .setImageResource(R.drawable.checkbox2_unselect);
        zhifubao_image
                .setImageResource(R.drawable.checkbox2_selected);

        BaseApplication.getInstance().addActivity(RenZhengActivity.this);
        mRequestManager = new RequestManager();
        mRequestManager.setResponseListener(this);
        postMap = new HashMap<String, String>();
        map = new HashMap<String,Object>();
        share = new SharePreferenceUtils(RenZhengActivity.this);
        phone = share.getString("user_mobile","");
        tv_commit = (Button) findViewById(R.id.tv_commit);
        bt_get_verification_code = (Button) findViewById(R.id.bt_get_verification_code);
        bt_get_verification_code.setText("获取验证码");
        bt_get_verification_code.setTextColor(Color.WHITE);
        //有效期2分钟
        timer = new TimeCountUtil(bt_get_verification_code, 120000, 1000);
        bt_get_verification_code.setClickable(true);
        phone_number = (EditText) findViewById(R.id.phone_number);
        phone_number.setText(phone);
        userName = (EditText) findViewById(R.id.et_username);
        zf_zh = (EditText) findViewById(R.id.zhangHao);
        yaoQing_code = (EditText) findViewById(R.id.yaoQing_code);
        imageCode = (EditText) findViewById(R.id.getImageCode);
        phone_code = (EditText) findViewById(R.id.getVerificationCode);
        image_code_view = (ImageView) findViewById(R.id.imageCode);
        String urlString = Constants.ServiceInterFace.ServerURL + "rest/api/v1.1/valid_code?valid_code_id="+uuId;
        URL imageUrl = null;
        Bitmap bitmap = null;
        try{
            imageUrl = new URL(urlString);
        }catch (MalformedURLException e) {
            // TODO: handle exception
            Log.e("TAG", "MalformedURLException");
            e.printStackTrace();
        }
        try{
            HttpURLConnection connection = (HttpURLConnection)imageUrl.openConnection();
            connection.setDoInput(true);
            connection.connect();
            //将得到的数据转换为InputStream
            InputStream is = connection.getInputStream();
            //将InputStream转换为Bitmap
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        }catch (IOException e) {
            // TODO: handle exception
            Log.e("TAG", "IOException");
        }
        if(bitmap == null){
            Log.i("TAG", "没取到数据");
        }else{
            image_code_view.setImageBitmap(bitmap);
        }
    }



    @Override
    public <T> void successResponse(T parsedGSON, int tag) {
        if (tag == Constants.RequestTag.getCodeTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                baseBean = (BaseBean) parsedGSON;
                if (baseBean.getResult().equals("success")) {
                    timer.start();
                    Toast.makeText(RenZhengActivity.this,baseBean.getMsg(),Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(RenZhengActivity.this,baseBean.getMsg(),Toast.LENGTH_SHORT).show();
                }
            }
        }
        if (tag == Constants.RequestTag.shiMingTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                baseBean = (BaseBean) parsedGSON;
                if (baseBean.getResult().equals("success")) {
                    Toast.makeText(RenZhengActivity.this,baseBean.getMsg(),Toast.LENGTH_SHORT).show();
                    BaseApplication.getInstance().removeActivity(RenZhengActivity.this);
                    finish();
                }else{
                    Toast.makeText(RenZhengActivity.this,baseBean.getMsg(),Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    public void errorResonse(String retmeg, int tag) {
        Toast.makeText(RenZhengActivity.this,R.string.noWangluo,Toast.LENGTH_SHORT).show();
    }
}
